<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas绘制矩形</title>
    <style>
        canvas{

        }
    </style>
</head>
<body>
<canvas width="500" height="400" id="canvas">
    您的浏览器不支持canvas，请更新！
</canvas>
</body>
<script>
    var canvas=document.getElementById('canvas');
    var ctx=canvas.getContext("2d");
    var x=0,y=0;
    var flag=1;
    ctx.lineWidth=20;
    ctx.fillStyle="red";
    var timer=setInterval(function(){
        ctx.clearRect(0,0,500,400);
        if(x>=450&&y==0){
            flag=2;
        } else if(x>=450&&y>=350){
            flag=3;
        }else if(x==0&&y>=350){
            flag=4
        }else if(x==0&&y==0){
            flag=1;
        }
        switch (flag){
            case 1:
                x++;
                ctx.fillRect(x,0,50,5);
                break;
            case 2:
                y++;
                ctx.fillRect(495,y,5,50);
                break;
            case 3:
                x--;
                ctx.fillRect(x,395,50,5);
                break;
            case 4:
                y--;
                ctx.fillRect(0,y,5,50);
                break;
        }
    },13)
</script>
</html>